package com.liuguangzhou.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @ClassName UserController
 * @Description: TODO
 * @Author liuguangzhou
 * @Date 2020/3/8
 * @Version V1.0
 **/
@Controller
public class UserController {
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        System.out.println("UserController.hello()");
        return "ok";
    }


    /**
    * 功能描述:
    * 〈测试thymeleaf〉
    * @Param: [model]
    * @Return: java.lang.String
    * @Author: liuguangzhou
    * @Date: 2020/3/8 21:53
    */
    @RequestMapping("/testThymeleaf")
    public String testThymeleaf(Model model){
        //把数据存入model  往前台传数据，可以传对象，可以传List
        model.addAttribute("name","samuel");
        //返回test.html
        return "test";
    }


    @RequestMapping("/add")
    public String add(){
        return "/user/add";
    }


    @RequestMapping("/update")
    public String update(){
        return "/user/update";
    }

    @RequestMapping("/login")
    public String login(){
        return "/login";
    }


    @RequestMapping("/toLogin")
    public String toLogin(String name,String password,Model model){
        /**
         * 使用Shiro编写认证操作
         */

        //1.获取Subject
        Subject subject=SecurityUtils.getSubject();

        //封装用户数据
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(name,password);

        try {
            subject.login(usernamePasswordToken);
            //login会调用 UserReaml执行认证操作doGetAuthenticationInfo 需要拦截那放开登录方法

            //登录成功
            //跳转到test.html
            return "redirect:/testThymeleaf";

            //shiro会通过异常来判断
        }catch (UnknownAccountException e){
            //登录失败:用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "/login";
        }catch (IncorrectCredentialsException e){
            //登录失败:密码错误
            model.addAttribute("msg", "密码错误");
            return "/login";

        }

    }

    @RequestMapping("/noAuth")
    public String onAuth(){
        return "/noAuth";
    }
}
